package com.audaque.springboot.foshanupload.schedule.abstra;

/**
 * @author zgb
 * @desc ...
 * @date 2021-12-24 21:27:03
 */

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.util.concurrent.ScheduledExecutorService;


@Slf4j
public abstract class AbstractSchedule implements SchedulingConfigurer {
    @Autowired
    ScheduledExecutorService scheduledExecutorService;


    //定时任务周期表达式
    private String cron;

    /**
     * @Description:  重写配置定时任务的方法
     * @param: scheduledTaskRegistrar
     * @return: void
     * @Author:
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.setScheduler(scheduledExecutorService);
        scheduledTaskRegistrar.addTriggerTask(
                //执行定时任务
                () -> {
                    try {
                        this.taskService();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                },
                //设置触发器
                triggerContext -> {
                    try {
                        cron = this.getCron();//获取定时任务周期表达式
                    } catch (Exception e) {
                        e.printStackTrace();log.error("异常栈:"+e);
                    }
                    CronTrigger trigger = new CronTrigger(cron);
                    return trigger.nextExecutionTime(triggerContext);
                }
        );

    }




    /**
     * @Description: 执行定时任务
     * @param:
     * @return: void
     * @Author:
     */
    public abstract void taskService() throws Exception;

    /**
     * @Description: 获取定时任务周期表达式
     * @param:
     * @return: java.lang.String
     * @Author:
     * @Date: 2020/8/28
     */
    public abstract String getCron() throws Exception;

}
